//辅助功能------------------------------------------------------------------------
/**
 * 视图渲染
 * @Param where 渲染位置
 * @Param templateName 模板名
 * @Param data 渲染数据
 * */
function viewToTemplate(where,templateName,data) {
    var html = $('script[type="text/'+templateName+'"]').html();//模板代码
    var arr=[];
    $("#"+where).html("");//清空tbody
    $.each(data, function (index, object) {
        arr.push(formatTemplate(object, html));
    });
    $("#"+where).append(arr.join(""));
}
function formatTemplate(object, tmpl,fun) {
    //m1 匹配到的字符{W} m2 字符的内容 W
    return tmpl.replace(/{(\w+)}/g,function (m1, m2) {
        if(!m2){
            return "";
        }
        if (object[m2] === null || object[m2] === undefined) {
            return "";
        }
        if (typeof fun == 'function' ){
            fun();
        }
        return object[m2];
    })
}

/**
 * 价格改变
 * @param data
 * @returns {*}
 */
function priceAdopt(data) {
    for (var i=0;i <data.length; i++){
        data[i].onePrice /= 100;
    }
    return data;
}
//功能实现-----------------------------------------------------------------------------------------
/**
 * 渲染购物车视图
 */
function renderCartView(){
    $.ajax({
        url:"/auth/queryShoppingWithConfirm",
        type:"post",
        success:function (res) {
            if(res.code == "200"){
                var data = res.extend.shoppings,
                    address = res.extend.addresses;
                priceAdopt(data);
                viewToTemplate("cart_view","cart_view",data);
                if (data.length <=0 ){
                    $("#address").html("没有商品,<a href='/list-view'>去购物</a>");
                }else {
                    addressViewRender(address);
                }
                countPrice(data)
                countTotalPrice(data);


            }else {
                $("#cart_table").html("<a href='/list-view'>去购物</a>")
                $("#total_price_table").html("")
            }
        },
        error:function (res) {
            sweetAlert({
                title:"提示",
                text:"还没有登陆",
                type:"warning",
                showCancelButton:false,
                confirmButtonColor:"#dd6b55",
                closeOnConfirm:false
            },function () {
                window.location.assign("/login")
            })
        }
    })
}

/**
 * 计算每行商品的总价格
 * @param data
 */
function countPrice(data){
    for(var i=0; i<data.length; i++) {
        var shopping = data[i];
        $("#single_totalPrice_"+shopping.shoppingId).html("价格：￥"+shopping.num*shopping.onePrice+".00");
    }
}

/**
 * 计算总商品的价格
 * @param data
 */
function countTotalPrice(data){
    var total=0;
    for(var i=0; i<data.length; i++) {
        total += data[i].num * data[i].onePrice;
    }
    $("#total_price_tbody").html("")
    $("#total_price_tbody").append("<th>总价</th>\n" +
        "                           <td data-title=\"Subtotal\">\n" +
        "                                        <span class=\"woocommerce-Price-amount amount\">\n" +
        "                                        <span class=\"woocommerce-Price-currencySymbol\"></span>\n" +
        "价格：￥"+             total                           +".00\n" +
        "                                         </span>\n" +
        "                                     </td>")
}

/**
 * 地址视图渲染
 * @param data
 */
function addressViewRender(data) {
    if (data.length <= 0){
    }else {
        console.log(2)
        viewToTemplate("address","address_view",data)
    }
    $("#address").append("<button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\" data-whatever=\"@mdo\">\n" +
        "        添加地址</button>")
}
/**
 * 购物车商品删除
 */
function delShoppingById(id) {
    sweetAlert({
        title:"是否删除",
        text:"你将无法更改!",
        type:"warning",
        showCancelButton:true,
        confirmButtonColor:"#dd6b55",
        closeOnConfirm:true
    },function (isConfired) {
        if(isConfired){
            $.ajax({
                url:"/auth/delShoppingById",
                type:"post",
                data:{"shoppingId":id},
                success:function (data) {
                    if(data.code == "200"){
                        sweetAlert("删除","商品已删除","success")
                        renderCartView();
                    }else {
                        sweetAlert("失败",data.msg,"error");
                    }

                }
            })
        }

    })
}
/**
 * 商品数量改变
 * @param obj
 */
function shoppingNumChange(obj) {
    var num=obj.value;
    if(num<0){
        sweetAlert("错误","请输入正数！","warning")
        return ;
    }
    //获取购物车id
    var shoppingId=$(obj).attr("shoppingId");
    $.post({
        url:"/auth/updateShoppingNum",
        data:{"shoppingId":shoppingId,"num":num},
        success:function (data ) {
            if(num == 0) {
                $(obj).parent().parent().parent().remove();
            }
            renderCartView();
        },
        error:function (res) {
            sweetAlert({
                title:"提示",
                text:"还没有登陆",
                type:"warning",
                showCancelButton:false,
                confirmButtonColor:"#dd6b55",
                closeOnConfirm:false
            },function () {
                window.location.assign("/login")
            })
        }
    })
    return ;
}




function address_select_option(){
    var city=[["成都","宜宾","自贡"],["遵义","赤水","贵阳"],["昆明","丽江"]]

    var country=[["郫县","双流","温江"],["翠屏区","高新区","江北区"],["富顺县","自流井区"]]
    $("#province").change(function () {
        var proviceId=$(this).val();
        if(proviceId==0){
            return ;
        }
        $("#city").empty();
        $("<option></option>").append("--请选择--").attr("value",0).appendTo($("#city"));
        $.each(city[proviceId-1],function (index, item) {
            $("<option></option>").append(item).attr("value",index+1).appendTo($("#city"));
        })
    })

    $("#city").change(function () {
        var cityId=$(this).val();
        if(cityId==0){
            return ;
        }
        $("#country").empty();
        $("<option></option>").append("--请选择--").appendTo($("#country"));
        $.each(country[cityId-1],function (index, item) {
            $("<option></option>").append(item).appendTo($("#country"));
        })
    })
}

//预加载-------------------------------------------------------------------------------------------
/**
 * 初始化
 */
$(document).ready(function(){
    //获取购物车的信息
    renderCartView();
    //地址初始化
    address_select_option();
    //提交地址
    $("#submit").click(function () {
        //简单校验一下省份等信息
        if($("#province").val()!=0&&$("#city").val()!=0&&$("#country").val()!=0){
            var data ={};
            data.province = $("#province :selected").text()
            data.city = $("#city :selected").text();
            data.country=$("#country :selected").text();
            data.name = $("#address_name").val();
            data.phone = $("#address_phone").val();
            data.street = $("#address_street").val()
            $.post({
                url:"/auth/addAddress",
                data: data,
                success:function (data) {
                   $("#exampleModal").modal("hide");
                   renderCartView();
                }
            })
        }else{
            alert("信息必须完善")
        }
    });
//    模态框关闭时间
    $("#myModal").on('hide.bs.modal',function () {
        // $("#province :selected").text();
        // $("#city :selected").text();
        // $("#country :selected").text();
        $("#address_name").val("");
        $("#address_phone").val("");
        $("#address_street").val("")

    })
})